package com.ccys.common.third.pubnub;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.pubnub.api.PNConfiguration;
import com.pubnub.api.PubNub;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author：XLY
 * @Date：2024/3/6 0006
 */


@Component
@Slf4j
@PropertySource(value = {"classpath:config/pubnub.properties", "file:./config/pubnub.properties", "file:./../config/pubnub.properties"}, ignoreResourceNotFound = true, encoding = "utf-8")
public class PubNubHelper {


    @Value("${pubnub.sub.key:}")
    private String subKey;

    @Value("${pubnub.pub.key:}")
    private String pubKey;

    private static final String CHANNEL_PREFIX = "consult_";

    private String channel;

    private PubNub pubnub;

    private void initPubnub(String uuid, String bookingId) {
        channel = CHANNEL_PREFIX + bookingId;
        List<String> channelList = Collections.singletonList(channel);
        try {
            PNConfiguration pnConfiguration = new PNConfiguration(uuid);
            pnConfiguration.setSubscribeKey(subKey);
            pnConfiguration.setPublishKey(pubKey);
            pubnub = new PubNub(pnConfiguration);
            pubnub.subscribe()
                    .channels(channelList)
                    .execute();

        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * {
     * "content": null,
     * "type": "file",
     * "file": {
     * "name_s3": "log-pubnub-0603202401561933285.jpg",
     * "name": "win10壁纸.jpg",
     * "url": "https://s3-ap-southeast-1.amazonaws.com/prv.staging.whitecoat.global/LogPubNub/8eff35ae-4b95-497b-9695-b293a70bc36d/log-pubnub-0603202401561933285.jpg",
     * "is_mood_log": false,
     * "height": 576,
     * "width": 1024,
     * "url_thumb": "https://s3-ap-southeast-1.amazonaws.com/prv.staging.whitecoat.global/LogPubNub/8eff35ae-4b95-497b-9695-b293a70bc36d/log-pubnub-thumb-0603202401561938111.jpg",
     * "id": "8ad2348c-281f-48ba-8ff2-769e27aa618d"
     * }
     * }
     * type分为file和 message ，如果是file就没有content，如果是message就没有file
     *
     * @param uuid      uuid = if(病人账号)？“patient”:“doctor”+accountId
     * @param bookingId bookingId
     * @param messageContent   消息内容
     */
    public void publish(String uuid, String bookingId, Message.MessageContent messageContent) {
        initPubnub(uuid, bookingId);
        try {
            if (Objects.nonNull(pubnub)) {
                pubnub.publish()
                        .channel(channel)
                        .message(messageContent)
                        .async((result, publishStatus) -> {
                            if (!publishStatus.isError()) {
                                // Message successfully published to specified channel.
                                log.info("publish success:" + channel);
                            }
                            // Request processing failed.
                            else {
                                // Handle message publish error
                                // Check 'category' property to find out
                                // issues because of which the request failed.
                                // Request can be resent using: [status retry];
                                log.error("publish failed:" + channel);
                            }
                        });
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            pubnub.unsubscribeAll();
        }

    }

    /**
     * 得到历史消息
     * @param bookingId bookingId
     * @return
     */
    public List<Message> getHistoryMessage(String bookingId) {
        String channelName = CHANNEL_PREFIX + bookingId;
        String url = "https://ps.pndsn.com/v3/history-with-actions/sub-key/" + subKey + "/channel/" + channelName + "?include_uuid=true";
        try {
            String resStr = HttpUtil.get(url);
            if (StringUtils.isNotEmpty(resStr)) {
                JSONObject resObject = JSONObject.parseObject(resStr);
                Integer status = resObject.getInteger("status");
                if (Objects.nonNull(status) && status.equals(200)) {
                    String messageStr = resObject.getJSONObject("channels").getString(channelName);
                    if (StringUtils.isNotEmpty(messageStr)) {
                        List<Message> messageList = JSONObject.parseArray(messageStr, Message.class);
                        return messageList;
                    }

                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 查询历史记录文件
     *
     * @param bookingId bookingId
     * @return 历史记录文件
     */
    public List<Message> getHistoryFile(String bookingId) {
        List<Message> historyMessage = getHistoryMessage(bookingId);
        if (CollectionUtils.isNotEmpty(historyMessage)) {
            List<Message> collect = historyMessage.stream().filter(x -> "file".equals(x.getMessage().getType())).collect(Collectors.toList());
            return collect;
        }
        return null;
    }


}


